import { login } from '@/api/user'
import { getToken, removeToken, setToken, setTime } from '@/utils/auth'
import { getUserInfo, getUserInfoByID } from '@/api/user'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userobj: {}
  },
  mutations: {
    // 储存token
    setToken(state, payload) {
      state.token = payload
      // 实现token的持久化
      setToken(payload)
      getToken()
    },
    // 删除token
    delToken(state) {
      state.token = ''
      removeToken()
    },
    // 储存用户信息
    setUserInfo(state, payload) {
      state.userobj = payload
    },
    // 删除用户信息
    delUserInfo(state) {
      state.userobj = {}
    }
  },
  actions: {
    // 登录
    async userLogin(context, payload) {
      const res = await login(payload)
      context.commit('setToken', res.data.data)
      setTime()
    },
    // 获取用户信息
    async userSetInfo(context) {
      const info = await getUserInfo()
      const res = await getUserInfoByID(info.data.data.userId)
      context.commit('setUserInfo', { ...info.data.data, ...res.data.data })
    },
    // 退出登录
    async userLogout(context) {
      context.commit('delUserInfo')
      context.commit('delToken')
    }
  }
}

